package com.example.SOPVersionChain.controller;

import com.example.SOPVersionChain.model.FileInfo;
import com.example.SOPVersionChain.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Controller
@RequestMapping("/versions")
public class VersionController {

    private final FileService fileService;

    @Autowired
    public VersionController(FileService fileService) {
        this.fileService = fileService;
    }

    /**
     * 显示版本列表页面
     * @param model 模型
     * @return 页面视图名称
     */
    @GetMapping
    public String listVersions(Model model) {
        List<FileInfo> fileList = fileService.getAllFiles();
        model.addAttribute("files", fileList);
        return "version-list";
    }

    /**
     * 下载文件
     * @param fileName 文件名
     * @return 文件资源
     * @throws IOException 如果文件不存在或无法读取
     */
    @GetMapping("/download/{fileName}")
    @ResponseBody
    public ResponseEntity<Resource> downloadFile(@PathVariable String fileName) throws IOException {
        String filePath = fileService.getFilePath(fileName);
        File file = new File(filePath);
        
        if (!file.exists()) {
            System.out.println("文件不存在：" + filePath);
            return ResponseEntity.notFound().build();
        }
        
        Resource resource = new FileSystemResource(file);
        String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString())
                .replace("+", "%20");
                
        return ResponseEntity.ok()
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename*=UTF-8''" + encodedFileName)
                .body(resource);
    }
} 